//
//  LRLoginViewController.m
//  本地生活圈
//
//  Created by admin on 15/8/14.
//  Copyright (c) 2015年 懒人. All rights reserved.
//

#import "LRLoginViewController.h"
#import "LRThirdCollectionViewCell.h"
#import "SSKeychain.h"
#import <WeiboSDK.h>

@interface LRLoginViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *userView;
@property (weak, nonatomic) IBOutlet UIView *pwdView;
@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UITextField *passWord;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *forgetBtn;
@property (weak, nonatomic) IBOutlet UIButton *rememberBtn;


/**
 *  第三方注册
 */
@property (nonatomic, strong) NSMutableArray *thirdArrays;


@end

@implementation LRLoginViewController


- (NSMutableArray *)thirdArrays
{
    if (!_thirdArrays)
    {
        _thirdArrays = [NSMutableArray array];
    }
    return _thirdArrays;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.titleLabel.text = @"登录";
    self.rightButton.hidden = YES;
    
    [self.thirdArrays addObject:@{@"name":@"新浪",@"icon":@"login_wb"}];
    [self.thirdArrays addObject:@{@"name":@"QQ",@"icon":@"login_qq"}];
    [self.thirdArrays addObject:@{@"name":@"微信",@"icon":@"login_wx"}];
    [self.thirdArrays addObject:@{@"name":@"豆瓣",@"icon":@"login_db"}];
    
    // 颜色设置
    self.userView.backgroundColor = kColor(114, 198, 252,1.0);
    self.userView.layer.cornerRadius = 5;
    self.pwdView.backgroundColor = kColor(114, 198, 252,1.0);
    self.pwdView.layer.cornerRadius = 5;
    self.loginBtn.backgroundColor = kColor(114, 198, 252, 1.0);
    self.loginBtn.layer.cornerRadius = 5;
    
    // 给忘记密码加下划线
    NSMutableAttributedString *title = [[NSMutableAttributedString alloc]initWithString:@"忘记密码?"];
    [title addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(0, title.length)];
    [title addAttribute:NSUnderlineColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, title.length)];
    [self.forgetBtn setAttributedTitle:title forState:UIControlStateNormal];
    
    self.flowLayout.itemSize = CGSizeMake(self.collectionView.bounds.size.width / 4, self.collectionView.bounds.size.height / (self.thirdArrays.count / 4));
    self.flowLayout.minimumLineSpacing = 0;
    self.flowLayout.minimumInteritemSpacing = 0;
    
    // 结束编辑状态
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(endEidt)];
    [self.view addGestureRecognizer:tap];
    
    // 监测输出状态 设置记住密码按钮可点击
    self.rememberBtn.selected = [[NSUserDefaults standardUserDefaults] boolForKey:kRememberPwd];
    [self.userName addTarget:self action:@selector(valueChange) forControlEvents:UIControlEventEditingChanged];
    [self.passWord addTarget:self action:@selector(valueChange) forControlEvents:UIControlEventEditingChanged];
    
    // 隐藏tabbar
    UIApplication *app = [UIApplication sharedApplication];
    LRTabBarViewController *tabBar = (LRTabBarViewController *)app.keyWindow.rootViewController;
    tabBar.tabBarView.hidden = YES;
}

- (void)endEidt
{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)valueChange
{
    if (self.userName.text.length > 0 && self.passWord.text.length > 0)
        self.rememberBtn.enabled = YES;
}
// 记住密码
- (IBAction)remember {
    self.rememberBtn.selected = !self.rememberBtn.selected;
    if (self.rememberBtn.selected)
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kRememberPwd];
    }
    else
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kRememberPwd];
}
// 忘记密码
- (IBAction)forget {
//    [MBProgressHUD showError:@"sorry i don't know"];
    
    // 新浪微博
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = @"www.baidu.com";
    request.scope = @"all";
    request.userInfo = @{@"SSO_From": @"SendMessageToWeiboViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    [WeiboSDK sendRequest:request];
}
// 登录
- (IBAction)login {
    if (self.userName.text.length <= 0 || self.passWord.text.length <= 0)
    {
        [MBProgressHUD showError:@"请输入账号密码"];
        return;
    }
    
    //用于存放参数
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.userName.text forKey:@"curr_account"];
    [param setObject:self.passWord.text forKey:@"password"];
    [param setObject:[LRFunction getTimeScamp] forKey:@"time"];
    NSArray *array = @[APP_ID,param[@"password"],param[@"time"],APP_IDENGER];
    [param setObject:[LRFunction md5StringFromArray:array] forKey:@"sign"];
    [param setObject:APP_ID forKey:@"app_id"];
    
    NSString *homeStr = @"http://www.qd-life.com/index.php?anu=api/1/user/dispose_login";
    [self.manager POST:homeStr parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {

        // 登录成功保存数据
        if ([responseObject[@"status"] isEqualToString:@"success"])
        {
            [[NSUserDefaults standardUserDefaults]setObject:self.userName.text forKey:@"userName"];
            [SSKeychain setPassword:self.passWord.text forService:kservice account:self.userName.text];
            
            [LRUserInfo pareseUserInfo:responseObject]; // 保存到内存
            
            [LRFunction saveUserInfoWithDict:responseObject]; // 保存到沙盒
            
            // 修改头像返回
            
            [self backClick];
        }
        else
            [MBProgressHUD showError:@"账号密码错误"];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD showError:@"网络错误,请检查网络"];
    }];
 
}
// 注册

#pragma mark - UICollectionView 数据源代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.thirdArrays.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifierId = @"LRThirdCollectionViewCell";
    LRThirdCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifierId forIndexPath:indexPath];

    cell.dict = self.thirdArrays[indexPath.row];
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    // 新浪微博
    [MBProgressHUD showError:@"进来了"];
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = @"www.baidu.com";
    request.scope = @"all";
    request.userInfo = @{@"SSO_From": @"SendMessageToWeiboViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    [WeiboSDK sendRequest:request];
}
@end
